/*
 * // +-------------------------------------------------------------------------------------------------
 * // |                 有你就好 [ 有节骨乃坚，无心品自端 ]     <http://encoding.wang>
 * // +-------------------------------------------------------------------------------------------------
 * // |                             独在异乡为异客         每逢佳节倍思亲
 * // +-------------------------------------------------------------------------------------------------
 * // |                 联系:   <707069100@qq.com>      <http://weibo.com/513778937>
 * // +-------------------------------------------------------------------------------------------------
 */

// -----------------------------------------------------------------------------------------------------
// +----------------------------------------------------------------------------------------------------
// |                   ErYang出品 属于小极品          共同学习    共同进步
// +----------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------

package wang.encoding.mroot.admin.common.task


import org.apache.shiro.session.Session
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.scheduling.annotation.Async
import org.springframework.scheduling.annotation.AsyncResult
import org.springframework.stereotype.Component
import wang.encoding.mroot.admin.common.constant.ConfigConst
import wang.encoding.mroot.admin.common.constant.Global
import wang.encoding.mroot.model.entity.system.Config
import wang.encoding.mroot.model.entity.system.Role
import wang.encoding.mroot.model.entity.system.Rule
import wang.encoding.mroot.model.entity.system.User
import wang.encoding.mroot.model.enums.StatusEnum
import wang.encoding.mroot.service.system.*
import java.math.BigInteger
import java.util.*
import java.util.concurrent.Future
import javax.cache.Cache
import kotlin.collections.ArrayList


/**
 * 异步调用
 *
 * @author ErYang
 */
@Component
class ControllerAsyncTask {

    @Autowired
    protected lateinit var configProperties: ConfigConst

    @Autowired
    protected lateinit var requestLogService: RequestLogService

    @Autowired
    protected lateinit var configService: ConfigService

    @Autowired
    protected lateinit var userService: UserService

    @Autowired
    private lateinit var ruleService: RuleService

    @Autowired
    private lateinit var roleService: RoleService

    @Autowired
    private lateinit var configCache: Cache<Any, Any>

    /**
     * 设置 session 中登录用户信息
     *
     * @param user User
     *
     * @return Future<String>
     */
    @Async("adminTaskExecutePool")
    fun initCurrentAdmin(user: User, session: Session): Future<String> {
        session.setAttribute(configProperties.adminSessionName,
                userService.aseDecryptData(user))
        return AsyncResult(">>>>>>>>initCurrentAdmin执行完毕<<<<<<<<")
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 重新设置 当前用户角色拥有的权限
     *
     * @param user User
     * @param session Session
     *
     * @return Future<String>
     */
    @Async("adminTaskExecutePool")
    fun initUserRoleHasRules(user: User, session: Session): Future<String> {
        // 权限
        val rules: MutableList<Rule> = mutableListOf()
        // 所属角色
        val roles: Set<Role> = roleService.listByUserId(user.id!!)!!
        if (roles.isNotEmpty()) {
            for (role: Role in roles) {
                val ruleList: TreeSet<Rule>? = ruleService.listByRoleId(role.id!!)
                if (null !== ruleList && ruleList.isNotEmpty()) {
                    for (rule: Rule in ruleList) {
                        if (BigInteger.ZERO != rule.pid) {
                            rules.add(rule)
                        }
                    }
                }
            }
            if (rules.isNotEmpty()) {
                // list 转为 tree
                val tree: List<Rule>? = Rule.list2Tree(rules)
                if (null != tree) {
                    // 用户权限菜单存放在 session 中
                    session.setAttribute(configProperties.adminMenuName, tree)
                }
            }
        }
        return AsyncResult(">>>>>>>>initUserRoleHasRules执行完毕<<<<<<<<")
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 清空请求日志
     *
     * @return Future<String>
     */
    @Async("adminTaskExecutePool")
    fun truncateRequestLog(): Future<String> {
        requestLogService.truncate()
        return AsyncResult(">>>>>>>>truncateRequestLog执行完毕<<<<<<<<")
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 重载系统配置信息
     *
     * @return Future<String>
     */
    @Async("adminTaskExecutePool")
    fun reloadConfigMap(): Future<String> {
        val configMap: MutableMap<String, Config> = mutableMapOf()
        val configWhereMap: Map<String, Any> = mapOf(Config.STATUS to StatusEnum.NORMAL.key)
        val configList: List<Config>? = configService.list(configWhereMap, null)
        if (null != configList && configList.isNotEmpty()) {
            for (i: Int in configList.indices) {
                val config: Config = configList[i]
                configMap[config.name!!] = config
            }
            Global.CONFIG_MAP = configMap
        }
        return AsyncResult(">>>>>>>>reloadConfigMap执行完毕<<<<<<<<")
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 根据 角色id 删除 角色-权限
     *
     * @param roleId BigInteger
     *
     * @return Future<String>
     */
    @Async("adminTaskExecutePool")
    fun removeByRoleId(roleId: BigInteger): Future<String> {
        ruleService.removeByRoleId(roleId)
        return AsyncResult(">>>>>>>>removeByRoleId执行完毕<<<<<<<<")
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 根据 角色id 删除 角色-权限
     *
     * @param roleIdArray Array<BigInteger>
     * @return Int
     */
    @Async("adminTaskExecutePool")
    fun removeByRoleIdArray(roleIdArray: ArrayList<BigInteger>?): Future<String> {
        ruleService.removeByRoleIdArray(roleIdArray)
        return AsyncResult(">>>>>>>>removeByRoleIdArray执行完毕<<<<<<<<")
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 根据 用户id 删除 用户-角色
     *
     * @param userId BigInteger
     *
     * @return Future<String>
     */
    @Async("adminTaskExecutePool")
    fun removeByUserId(userId: BigInteger): Future<String> {
        roleService.removeByUserId(userId)
        return AsyncResult(">>>>>>>>removeByUserId执行完毕<<<<<<<<")
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 根据 用户id 删除 用户-角色
     *
     * @param userIdArray Array<BigInteger>
     * @return Int
     */
    @Async("adminTaskExecutePool")
    fun removeByUserIdArray(userIdArray: ArrayList<BigInteger>?): Future<String> {
        roleService.removeByUserIdArray(userIdArray)
        return AsyncResult(">>>>>>>>removeByUserIdArray执行完毕<<<<<<<<")
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 清空所有缓存
     *
     * @param userIdArray Array<BigInteger>
     * @return Int
     */
    @Async("adminTaskExecutePool")
    fun clearAllCache(): Future<String> {
        configCache.removeAll()
        return AsyncResult(">>>>>>>>clearAllCache执行完毕<<<<<<<<")
    }

    // -------------------------------------------------------------------------------------------------

}

// -----------------------------------------------------------------------------------------------------

// End ControllerAsyncTask class

/* End of file ControllerAsyncTask.kt */
/* Location: ./src/main/kotlin/wang/encoding/mroot/admin/common/task/ControllerAsyncTask.kt */

// -----------------------------------------------------------------------------------------------------
// +----------------------------------------------------------------------------------------------------
// |                           ErYang出品 属于小极品  O(∩_∩)O~~   共同学习    共同进步
// +----------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------

// -----------------------------------------------------------------------------------------------------
